package org.lds.hotkey.worker.common.model;

import lombok.Data;

import java.util.*;

@Data
public class SlidingWindow {
    private final Queue<Timestamp> timestampDeque = new LinkedList<>();
    /**
     * 时间窗口大小，单位为毫秒
     */
    private final long windowSize;
    /**
     * 窗口允许通过的最大阈值
     */
    private final long threshold;

    public SlidingWindow(long windowSize, long threshold) {
        this.windowSize = windowSize;
        this.threshold = threshold;
    }

    public boolean addCount(int count) {
        if (count >= threshold) return true;

        long currentTime = System.currentTimeMillis();
        timestampDeque.offer(Timestamp.builder().timestamp(currentTime).count(count).build());

        // 移除过期的时间戳
        long cha = currentTime - timestampDeque.peek().getTimestamp();
        while (timestampDeque.size() > 1 && cha > windowSize) {
            System.out.println(cha+"ms windowSize="+windowSize+"ms");
            timestampDeque.poll();
        }

        // 求和
        int sum = 0;
        for (Timestamp timestamp : timestampDeque) {
            sum += timestamp.getCount();
        }

        boolean isHot = sum >= threshold;
        if (isHot) {
            timestampDeque.clear();
        }
        return isHot;
    }

    private int sum() {
        int sum = 0;
        return sum;
    }

    public static void main(String[] args) {
        SlidingWindow slidingWindow = new SlidingWindow(100000, 7);

        // 模拟添加按键使用情况
        for (int i = 0; i < 10; i++) {
            if (i == 7) {
                System.out.println("111");
                System.out.println("Hot Keys: " + slidingWindow.addCount(1));
            } else {
                System.out.println("Hot Keys: " + slidingWindow.addCount(1));
            }
        }
    }
}